package C004;

import java.util.Arrays;

/**
 * ClassName: SelectionSort
 * Package: C004
 * Description:
 *
 * @Author BCXJ
 * @Create 2024/11/26 20:29
 * @Version 1.0
 * @Since 1.0
 */
public class Sort {
    public static void main(String[] args) {
        int n = 100000;
        int size = 1;
        int min = 1;
        int max = 100;
        for (int i = 0; i < n; i++) {
            int[] arr = generateRandomArray(size, min, max);
            int[] arr2 = Arrays.copyOfRange(arr, 0, arr.length);
            int[] arr3 = Arrays.copyOfRange(arr, 0, arr.length);
            int[] arr4 = Arrays.copyOfRange(arr, 0, arr.length);
            selectionSort(arr);
            Arrays.sort(arr2);
            bubbleSort(arr3);
            InsertionSort(arr4);
            if(!equalsArr(arr, arr2) || !equalsArr(arr, arr3) || !equalsArr(arr, arr4)) {
                System.out.println("error!!!!");
                System.out.println(Arrays.toString(arr));
                System.out.println(Arrays.toString(arr2));
                System.out.println(Arrays.toString(arr3));
                return;
            }
        }

        System.out.println("test succcess");
    }

    private static void InsertionSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1] ; j--) {
                swap(arr, j, j + 1);
            }
        }
    }


    private static void bubbleSort(int[] arr) {
        for (int i = arr.length - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                if(arr[j] > arr[j+1]) {
                    swap(arr, j, j+1);
                }
            }
        }
    }

    public static void selectionSort(int[] arr) {
        int minIndex = -1;
        for (int i = 0; i < arr.length; i++) {
            minIndex = i;
            for (int j = i; j < arr.length; j++) {
                // 找打最小的下标
                if(arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            swap(arr, i, minIndex);
        }
    }

    private static void swap(int[] arr, int i, int minIndex) {
        if(i == minIndex) {
            return;
        }
        arr[i] = arr[i] ^ arr[minIndex];
        arr[minIndex] = arr[i] ^ arr[minIndex];
        arr[i] = arr[i] ^ arr[minIndex];
    }


    public static int[] generateRandomArray(int size, int min, int max) {
        int[] arr = new int[size];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = min + (int)(Math.random() * max);
        }
        return arr;
    }

    public static boolean equalsArr(int[] arr, int[] arr2) {
        if(arr.length != arr2.length) {
            return false;
        }
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] != arr2[i]) {
                return false;
            }
        }

        return true;
    }
}
